<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true">
          <el-form-item label="工资发放日期" prop="salaryPaymentDate">
            <el-date-picker v-model="queryParams.salaryPaymentDate" value-format="YYYY-MM" type="month" placeholder="请选择月份" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['business:laborCostTotal:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['business:laborCostTotal:edit']"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['business:laborCostTotal:remove']"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['business:laborCostTotal:export']">导出</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Upload" @click="handleUpload">导入</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExportTemplate">导出模板</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="laborCostTotalList" @selection-change="handleSelectionChange" :height="windowHeight">
        <el-table-column fixed type="selection" width="55" align="center" />
        <el-table-column fixed label="人员信息" align="center" prop="name" />
        <el-table-column fixed label="岗位" align="center" prop="post" />
        <el-table-column label="基础工资" align="center" prop="basePay" />
        <el-table-column label="岗位津贴" align="center" prop="postAllowance" />
        <el-table-column label="其他津贴" align="center" prop="otherAllowance" />
        <el-table-column label="服装补贴" align="center" prop="clothingAllowance" />
        <el-table-column label="应发工资" align="center" prop="salaryPayable" />
        <el-table-column label="加班费" align="center" prop="overtimePay" />
        <el-table-column label="未满月工资扣除" align="center" prop="deductWorkFullHoursPay" />
        <el-table-column label="扣当月个人公积金" align="center" prop="deductingDyPersonalProvidentFund" />
        <el-table-column label="补服装补贴" align="center" prop="patchClothingSubsidy" />
        <el-table-column label="其他扣除" align="center" prop="otherDeduct" />
        <el-table-column label="月度优秀员工" align="center" prop="monthlyOutstandingEmployee" />
        <el-table-column label="工资实发数" align="center" prop="actualSalaryPaid" />
        <el-table-column label="当月社保" align="center" prop="dySocialSecurity" />
        <el-table-column label="当月单位公积金" align="center" prop="dyUnitProvidentFund" />
        <el-table-column label="下月雇主责任险" align="center" prop="employerLiabilityInsurance" />
        <el-table-column label="劳务管理费" align="center" prop="laborManagementFee" />
        <el-table-column label="劳务费用合计" align="center" prop="totalLaborCosts" />
        <el-table-column label="工资发放日期" width="110" align="center" prop="salaryPaymentDate" />
        <el-table-column label="备注" align="center" prop="remark" show-overflow-tooltip />
        <el-table-column fixed="right" label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['business:laborCostTotal:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button
                link
                type="primary"
                icon="Delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['business:laborCostTotal:remove']"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改劳务对话框 -->
    <!-- <el-dialog :title="dialog.title" v-model="dialog.visible" append-to-body>
      <el-form ref="laborCostTotalFormRef" :model="form" :rules="rules" label-width="125px">
        <el-form-item label="人员信息" prop="peopleInfoId">
          <el-cascader
            v-model="form.peopleInfoId"
            placeholder="请输入人员信息"
            :options="useCompany.companyRYList"
            filterable
            :props="{ value: 'id',label: 'name',children: 'children'}"
            :show-all-levels="false"
            @change="selectPeople"
          />
        </el-form-item>
        <el-form-item label="岗位" prop="post">
          <el-input v-model="form.post" placeholder="请输入岗位" />
        </el-form-item>
        <el-form-item label="基础工资" prop="basePay">
          <el-input v-model="form.basePay" placeholder="请输入基础工资" />
        </el-form-item>
        <el-form-item label="岗位津贴" prop="postAllowance">
          <el-input v-model="form.postAllowance" placeholder="请输入岗位津贴" />
        </el-form-item>
        <el-form-item label="其他津贴" prop="otherAllowance">
          <el-input v-model="form.otherAllowance" placeholder="请输入其他津贴" />
        </el-form-item>
        <el-form-item label="服装补贴" prop="clothingAllowance">
          <el-input v-model="form.clothingAllowance" placeholder="请输入服装补贴" />
        </el-form-item>
        <el-form-item label="应发工资" prop="salaryPayable">
          <el-input v-model="form.salaryPayable" placeholder="请输入应发工资" />
        </el-form-item>

        <el-form-item label="加班费" prop="overtimePay">
          <el-input v-model="form.overtimePay" placeholder="请输入加班费" />
        </el-form-item>
        <el-form-item label="未满月工资扣除" prop="deductWorkFullHoursPay">
          <el-input v-model="form.deductWorkFullHoursPay" placeholder="请输入未满月工资扣除" />
        </el-form-item>
        <el-form-item label="扣当月个人公积金" prop="deductingDyPersonalProvidentFund">
          <el-input v-model="form.deductingDyPersonalProvidentFund" placeholder="请输入扣当月个人公积金" />
        </el-form-item>
        <el-form-item label="补服装补贴" prop="patchClothingSubsidy">
          <el-input v-model="form.patchClothingSubsidy" placeholder="请输入补服装补贴" />
        </el-form-item>
        <el-form-item label="其他扣除" prop="otherDeduct">
          <el-input v-model="form.otherDeduct" placeholder="请输入其他扣除" />
        </el-form-item>
        <el-form-item label="月度优秀员工" prop="monthlyOutstandingEmployee">
          <el-input v-model="form.monthlyOutstandingEmployee" placeholder="请输入月度优秀员工" />
        </el-form-item>
        <el-form-item label="工资实发数" prop="actualSalaryPaid">
          <el-input v-model="form.actualSalaryPaid" placeholder="请输入工资实发数" />
        </el-form-item>
        <el-form-item label="当月社保" prop="dySocialSecurity">
          <el-input v-model="form.dySocialSecurity" placeholder="请输入当月社保" />
        </el-form-item>
        <el-form-item label="当月单位公积金" prop="dyUnitProvidentFund">
          <el-input v-model="form.dyUnitProvidentFund" placeholder="请输入当月单位公积金" />
        </el-form-item>
        <el-form-item label="下月雇主责任险" prop="employerLiabilityInsurance">
          <el-input v-model="form.employerLiabilityInsurance" placeholder="请输入下月雇主责任险" />
        </el-form-item>
        <el-form-item label="劳务管理费" prop="laborManagementFee">
          <el-input v-model="form.laborManagementFee" placeholder="请输入劳务管理费" />
        </el-form-item>
        <el-form-item label="劳务费用合计" prop="totalLaborCosts">
          <el-input v-model="form.totalLaborCosts" placeholder="请输入劳务费用合计" />
        </el-form-item>
        <el-form-item label="工资发放日期" prop="salaryPaymentDate">
          <el-date-picker v-model="form.salaryPaymentDate" value-format="YYYY-MM-DD" type="date" placeholder="请选择工资发放日期" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog> -->
  </div>

  <!-- 导入数据 -->
  <el-dialog class="importData" v-model="importDataDialog" title="导入工资数据" width="500">
    <!-- <el-col :span="18"> -->
    <el-form :model="importDataForm" ref="importDataFormRef" :rules="importDataRules">
      <el-form-item label="导入公司" prop="companyId">
        <el-select class="slese" v-model="importDataForm.companyId" placeholder="请选择公司" ref="selectRef" style="width: 240px;">
          <el-option class="communityDropdown" v-for="item in companyList" :key="item.companyId" :label="item.companyName" :value="item.companyId" />
        </el-select>
      </el-form-item>
    </el-form>
    <!-- </el-col> -->
    <!-- <el-col :span="6" class="text-center"> -->
    <div class="import-btn">
      <el-upload class="upload-demo" action=" " :limit="1" :before-upload="beforeAvatarUpload" :http-request="handleUploadFiles" ref="fileUploadRef">
        <el-button type="primary" plain>选择文件</el-button>
      </el-upload>
    </div>
    <!-- </el-col> -->
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cannelImportData">取消</el-button>
        <!-- <el-button :loading="buttonImportDataLoading" type="primary" @click="cannelImportData"> 确定 </el-button> -->
      </div>
    </template>
  </el-dialog>
</template>

<script setup name="LaborCostTotal" lang="ts">
import { listLaborCostTotal, getLaborCostTotal, delLaborCostTotal, addLaborCostTotal, updateLaborCostTotal } from '@/api/business/wages';
import { LaborCostTotalVO, LaborCostTotalQuery, LaborCostTotalForm } from '@/api/business/wages/types';
import { getPeopleInfo } from '@/api/business/peopleInfo';
import { listCompany } from '@/api/business/company';

import useCompanyStore from '@/store/modules/company';
import request from '@/utils/request';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const router = useRouter();

const useCompany = useCompanyStore();
const laborCostTotalList = ref<LaborCostTotalVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const laborCostTotalFormRef = ref<ElFormInstance>();

const initFormData: LaborCostTotalForm = {
  companyId: useCompany.companyId,
  laborCostTotalId: undefined,
  peopleInfoId: undefined,
  post: undefined,
  overtimePay: undefined,
  basePay: undefined,
  postAllowance: undefined,
  otherAllowance: undefined,
  clothingAllowance: undefined,
  salaryPayable: undefined,
  deductWorkFullHoursPay: undefined,
  deductingDyPersonalProvidentFund: undefined,
  patchClothingSubsidy: undefined,
  otherDeduct: undefined,
  monthlyOutstandingEmployee: undefined,
  actualSalaryPaid: undefined,
  dySocialSecurity: undefined,
  dyUnitProvidentFund: undefined,
  employerLiabilityInsurance: undefined,
  laborManagementFee: undefined,
  totalLaborCosts: undefined,
  salaryPaymentDate: undefined,
  remark: undefined,
}
const data = reactive<PageData<LaborCostTotalForm, LaborCostTotalQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 100,
    companyId: useCompany.companyId,
    laborCostTotalId: undefined,
    peopleInfoId: undefined,
    post: undefined,
    overtimePay: undefined,
    basePay: undefined,
    postAllowance: undefined,
    otherAllowance: undefined,
    clothingAllowance: undefined,
    salaryPayable: undefined,
    deductWorkFullHoursPay: undefined,
    deductingDyPersonalProvidentFund: undefined,
    patchClothingSubsidy: undefined,
    otherDeduct: undefined,
    monthlyOutstandingEmployee: undefined,
    actualSalaryPaid: undefined,
    dySocialSecurity: undefined,
    dyUnitProvidentFund: undefined,
    employerLiabilityInsurance: undefined,
    laborManagementFee: undefined,
    totalLaborCosts: undefined,
    salaryPaymentDate: undefined,
    remark: undefined,
    params: {
    }
  },
  rules: {
    laborCostTotalId: [
      { required: true, message: "劳务表id不能为空", trigger: "blur" }
    ],
    peopleInfoId: [
      { required: true, message: "人员信息id不能为空", trigger: "blur" }
    ],
    post: [
      { required: true, message: "岗位不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

const importDataDialog = ref(false)
const companyList = ref()
const importDataForm = ref({
  companyId:undefined,
})
const importDataFormRef = ref<ElFormInstance>();

const importDataRules = ref({
  companyId: [
    { required: true, message: "公司不能为空", trigger: "blur" }
  ]
})

const companyQueryParams = ref({
  pageNum: 1,
  pageSize: 100,
  companyId: undefined,
})

/** 查询劳务列表 */
const getList = async () => {
  loading.value = true;
  queryParams.value.companyId = useCompany.companyId
  const res = await listLaborCostTotal(queryParams.value);
  laborCostTotalList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
// const cancel = () => {
//   reset();
//   dialog.visible = false;
// }

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  laborCostTotalFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: LaborCostTotalVO[]) => {
  ids.value = selection.map(item => item.laborCostTotalId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  // sessionStorage.setItem('houseCost',JSON.stringify(queryParams.value))
  router.push({ path: '/administration/wagesAdd', query: { type:'add' } })

  // reset();
  // dialog.visible = true;
  // dialog.title = "添加劳务";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: LaborCostTotalVO) => {
  // sessionStorage.setItem('houseCost',JSON.stringify(queryParams.value))
  router.push({ path: '/administration/wagesAdd', query: { type:'edit',id: row?.laborCostTotalId } })

  // reset();
  // const _laborCostTotalId = row?.laborCostTotalId || ids.value[0]
  // const res = await getLaborCostTotal(_laborCostTotalId);
  // Object.assign(form.value, res.data);
  // dialog.visible = true;
  // dialog.title = "修改劳务";
}

/** 提交按钮 */
// const submitForm = () => {
//   laborCostTotalFormRef.value?.validate(async (valid: boolean) => {
//     if (valid) {
//       buttonLoading.value = true;
//       if (form.value.laborCostTotalId) {
//         await updateLaborCostTotal(form.value).finally(() =>  buttonLoading.value = false);
//       } else {
//         await addLaborCostTotal(form.value).finally(() =>  buttonLoading.value = false);
//       }
//       proxy?.$modal.msgSuccess("修改成功");
//       dialog.visible = false;
//       await getList();
//     }
//   });
// }

/** 删除按钮操作 */
const handleDelete = async (row?: LaborCostTotalVO) => {
  const _laborCostTotalIds = row?.laborCostTotalId || ids.value;
  await proxy?.$modal.confirm('是否确认删除劳务编号为"' + _laborCostTotalIds + '"的数据项？').finally(() => loading.value = false);
  await delLaborCostTotal(_laborCostTotalIds);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 查询公司列表 */
const getCompanyList =async () => {
  companyQueryParams.value.companyId = useCompany.companyId
  const res = await listCompany(companyQueryParams.value);
  companyList.value = res.rows;
}


// 导入按钮操作
const handleUpload = () => {
  importDataDialog.value = true
  importDataForm.value.companyId = useCompany.companyId
}

/** 取消导入数据 */
const cannelImportData = async () => {
  importDataDialog.value = false
  restImportData()
}

/* 重置导入数据 */
const restImportData = () => {
  importDataForm.value.companyId = undefined
  importDataFormRef.value?.resetFields();
}

/** 上传文件前 */
const beforeAvatarUpload = (file:any) =>{
  let index = file.name.lastIndexOf('.')
  let str = file.name.substr(index + 1)
  if (!importDataForm.value.companyId) {
    ElMessage.error('请选择导入公司!')
    return false
  } else if ( ['xlsx'].indexOf(str.toLowerCase()) == -1) {
    ElMessage.error('请选择正确的文件！')
    return false
  }
  return true
}

/** 上传文件 */
const handleUploadFiles = (file: any) => {
  let data = new FormData();
  data.append('companyId', importDataForm.value.companyId);
  data.append('file', file.file);
  request({
      url: '/business/laborCostTotal/excelPeopleAll',
      headers: {
        "Content-Type": "multipart/form-data",
        isToken: true
      },
      method: 'post',
      data:data,
      onUploadProgress: function (e) {
        proxy?.$modal.loading("正在上传文件，请稍候...");
    }
  }).then(res=> {
      proxy?.$modal.closeLoading();
      /* if (res.length > 0) {
        proxy?.$modal.closeLoading();
        fileUploadRef.value?.handleRemove(file);
      }else{
        proxy?.$modal.closeLoading();
      } */
  })
  return true;
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('business/peopleInfo/export', {
    ...queryParams.value
  }, `peopleInfo_${new Date().getTime()}.xlsx`)
}

/** 导出按钮操作 */
const handleExportTemplate = () => {
  proxy?.$download.downloadTemplate('2')
}

// const selectPeople = async() => {
//   const res = await getPeopleInfo(form.value.peopleInfoId[form.value.peopleInfoId.length-1]);
//   form.value.post = res.data.post
//   form.value.basePay = res.data.basePay
//   form.value.postAllowance = res.data.postAllowance
//   form.value.otherAllowance = res.data.otherAllowance
//   form.value.clothingAllowance = res.data.clothingAllowance
//   form.value.salaryPayable = res.data.salaryPayable
// }

//用深度监听单位变化
watch(() => useCompany.companyId, (newVal, oldVal) => {
  getList()
}, { deep: true });

const windowHeight = ref(500)
onMounted(async () => {
  await getCompanyList();
  const date = new Date();
  var currentYear = date.getFullYear();
  const currentMonth = date.getMonth() + 1;
  queryParams.value.salaryPaymentDate = currentYear+'-'+currentMonth
  await getList();

  let pageHeight = Math.max(
    document.documentElement.clientHeight,
    window.innerHeight || 0
  );
  windowHeight.value = pageHeight - 360
});
</script>
